<template>
  <div class="add-Notice-message">
    <el-dialog class="show-notice-dialog" width="70%" title="添加通知信息" :visible.sync="addNoticeSync"
               :before-close="handleCloseDialog">
      <el-card shadow="never">
        <div class="add-Notice-inputBox">
          <el-form label-width="100px" :inline="true" :model="noticeInfo" ref="addNoticeForm" :rules="addNoticeRules">
            <el-form-item label="通知标题：" prop="noticeTitle">
              <el-input size="small" placeholder="请输入通知标题" v-model="noticeInfo.noticeTitle"  clearable class="add-notice-input"/>
            </el-form-item>
            <el-form-item label="通知类型：" prop="noticeType">
              <el-select  size="small"  v-model="noticeInfo.noticeType" clearable placeholder="请选择通知类型" class="add-notice-input">
                <el-option  v-for="item in typeOptions" :key="item.value" :value="item.value" :label="item.label"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item  v-show="noticeInfo.noticeType===1" label="被通知人：">
              <el-select size="small"   multiple v-model="noticeInfo.noticeUserList" placeholder="请选择被通知人"
                         reserve-keyword
                         filterable
                         clearable
                         collapse-tags
                         remote :remote-method="remoteNoticeUser" :loading="remoteUserLoading" class="add-notice-input">
                <el-option  v-for="item in remoteUserData" :key="item.id" :value="item.id" :label="item.name">
                  <span style="float: left">{{ item.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.idNumber }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-show="noticeInfo.noticeType===1"  label="被通知分类：">
              <el-select size="small"  multiple v-model="noticeInfo.noticeCategoryList" placeholder="请选择被通知人分类"
                         reserve-keyword
                         filterable
                         collapse-tags
                         clearable
                         remote :remote-method="remoteNoticeCategory" :loading="remoteCategoryLoading" class="add-notice-input">
                <el-option  v-for="item in remoteCategoryData" :key="item.id" :value="item.id" :label="item.categoryName">
                  <span style="float: left">{{ item.categoryName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.categoryCode }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <VueEditor maxLength="2000" placeholder="请输入通知正文..." class="editor"
                     v-model="noticeInfo.noticeContent" :editorToolbar="customToolbar"/>
        </div>
        <div class="dialog-footer">
          <el-button @click="handleCloseDialog">取 消</el-button>
          <el-button type="primary" @click="handleAddNotice">确认添加</el-button>
        </div>
      </el-card>
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import store from '@/store'
import { VueEditor,Quill } from 'vue2-editor'
import { selectByName } from '@/request/user/user-api'
import { GetCategoryByNameApi } from '@/request/category/category-api'
import { AddNoticeApi } from '@/request/message/notice-api'
let fontList = ['SimSun','宋体','楷体','黑体','幼圆']
Quill.imports['formats/font'].whitelist = fontList
Quill.register(Quill.imports['formats/font'])

let fontSizeList = [false, '10px','12px','14px','16px','20px','24px']
Quill.imports['attributors/style/size'].whitelist = fontSizeList
Quill.register(Quill.imports['attributors/style/size'])
export default {
  computed: {
    ...mapState({
      addNoticeSync: state => state.NoticeEdit.addNoticeSync,
    })
  },
  data(){
    return{
      remoteUserLoading:false,
      remoteCategoryLoading:false,
      noticeInfo:{
        noticeType:null,
        noticeTitle:null,
        noticeContent:null,
        noticeUserList:[],
        noticeCategoryList:[],
      },
      typeOptions:[
        {value:0,label:'全体通知'},
        {value: 1,label: '个人通知'}
      ],
      remoteUserData:[],
      remoteCategoryData:[],
      customToolbar: [
        [{ size: fontSizeList }],
        [{ font: fontList }],
        [{ 'header': [1, 2, 3, 4, 5, 6, false] }], //几级标题
        ['bold', 'italic', 'underline', 'strike'], //加粗，斜体，下划线，删除线
        ['blockquote', 'code-block'], //引用，代码块
        [{ 'list': 'ordered' }, { 'list': 'bullet' }], //列表
        [{ 'script': 'sub' }, { 'script': 'super' }], // 上下标
        [{ 'indent': '-1' }, { 'indent': '+1' }], // 缩进
        [{ 'direction': 'rtl' }], // 文本方向
        [{ 'color': [] }, { 'background': [] }], // 字体颜色，字体背景颜色
        // [{'font': []}], //字体
        [{ 'align': [] }], //对齐方式
        ['clean'], //清除字体样式
        // ['image', 'video'] //上传图片、上传视频
      ],
      addNoticeRules:{
        noticeTitle:{required:true,message:'请输入标题',trigger:'blur'},
        noticeType:{required:true,message:'请选择类型',trigger:'blur'},
      }
    }
  },
  methods: {
    close () {
      this.remoteCategoryData=null
      this.remoteUserData=null
      this.noticeInfo={
        noticeType:null,
            noticeTitle:null,
            noticeContent:null,
            noticeUserList:[],
            noticeCategoryList:[],
      }
      //取消单项验证
      this.$nextTick(() => {
        this.$refs['addNoticeForm'].clearValidate()
      })
      store.commit('NoticeEdit/changeAddNoticeSync', false)
    },
    async remoteNoticeUser (query) {
      if (query && query !== '') {
        this.remoteUserLoading = true;
        this.remoteUserData=[]
        //发送请求
        let res = await selectByName(query)
        if (res&&res.code===200){
          this.remoteUserData=res.data
          this.remoteUserLoading=false
        }else {
          this.$message.error("获取用户失败")
          this.remoteUserLoading=false
        }
      }
    },
    async remoteNoticeCategory (query) {
      if (query && query !== '') {
        this.loading = true;
        this.remoteUserData=[]
        //发送请求
        let res = await GetCategoryByNameApi(query)
        if (res&&res.code===200){
          this.remoteCategoryData=res.data
          this.remoteCategoryLoading=false
        }else {
          this.$message.error("获取分类失败")
          this.remoteCategoryLoading=false
        }
      }
    },
    handleAddNotice(){
      this.$refs.addNoticeForm.validate(valid => {
        if (!valid) {
          this.$message.error('存在错误内容，请完善信息！')
          return false
        } else {
          this.$confirm('确定添加该专家信息吗？', '提示',
              {
                'confirmButtonText': '确定',
                'cancelButtonText': '取消',
                'type': 'warning'
              }).then(async () => {
            let res = await AddNoticeApi(this.noticeInfo)
            if (res&&res.code===200){
              this.$message.success("添加消息成功")
              this.close()
              this.$parent.handleQuery()
            }else {
              this.$message.error(res.msg?res.msg:"添加失败")
            }
          }).catch((e) => {
            if (e === 'cancel') {
              this.$message.info('取消添加')
            } else {
              this.$message.error('未知错误！')
            }
          });
        }
      });
    },
    handleCloseDialog () {
      this.$confirm('确定取消添加通知信息吗？', '提示', {
        'confirmButtonText': '确定',
        'cancelButtonText': '取消',
        'type': 'info'
      }).then(async () => {
        this.close()
      }).catch((e) => {
        if (e === 'cancel') {
        }
      })
    }
  },watch:{
    noticeType:{
      immediate:true,
      handler(val,old){
        if (val){
          this.noticeCategoryList=[]
          this.noticeUserList=[]
        }
      }
    }
  }
}
</script>
<style scoped lang="less">
.add-Notice-message{
  .show-notice-dialog{

    .add-Notice-inputBox{
      .add-notice-input{
        width: 190px;
      }
      .editor {
        /deep/ .ql-container {
          overflow-y: scroll;
          max-height: 240px !important;
        }
      }
    }
    .dialog-footer{
      text-align: center;
      margin-top: 20px;
    }
  }
}
</style>
